﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml.Serialization;
using mediaPrime.Logger;

namespace mediaPrime.Sdk
{
    /// <summary>
    /// Descriptor for an Extension
    /// </summary>
    [XmlRoot("Extension")]
    public class ExtensionInfo
    {
        private ImageSource icon;

        /// <summary>
        /// Type of the Extension
        /// </summary>
        public ExtensionType Type { get; set; }

        /// <summary>
        /// Unique identifier
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// Name of the Extension
        /// </summary>
        [XmlIgnore]
        public string Name
        {
            get
            {
                return getLocalizedText(Names);
            }
        }
        [XmlElement("Name")]
        public List<LocalizedString> Names { get; set; }


        /// <summary>
        /// Extensions's author
        /// </summary>
        public string Author { get; set; }

        public string Category { get; set; }

        /// <summary>
        /// A description of the Extension
        /// </summary>
        [XmlIgnore]
        public string Description
        {
            get
            {
                return getLocalizedText(Descriptions);
            }
        }

        [XmlElement("Description")]
        public List<LocalizedString> Descriptions { get; set; }

        /// <summary>
        /// Changelog of the current version
        /// </summary>
        [XmlIgnore]
        public string Changelog
        {
            get
            {
                return getLocalizedText(Changelogs);
            }
        }

        [XmlElement("Changelog")]
        public List<LocalizedString> Changelogs { get; set; }

        /// <summary>
        /// File name of the Plugin
        /// </summary>
        public string File { get; set; }

        /// <summary>
        /// Path to the Plugin DLL
        /// </summary>
        [XmlIgnore]
        public string Path { get; set; }

        /// <summary>
        /// Patht to directory of the Plugin
        /// </summary>
        [XmlIgnore]
        public string Directory { get; set; }

        /// <summary>
        /// Minimum required version of mediaPrime to use this Extension
        /// </summary>
        public string MinCoreVersion { get; set; }

        /// <summary>
        /// File name of a screenshot of this Extension
        /// </summary>
        public string Screenshot { get; set; }

        /// <summary>
        /// Path to icon file (PNG), only used for serialization
        /// </summary>
        [XmlElement("Icon")]
        public string XmlIcon { get; set; }

        [XmlIgnore]
        public ImageSource Icon
        {
            get
            {
                if (icon == null)
                {
                    // Load icon, if not loaded                   

                    try
                    {
                        var iconPath = System.IO.Path.Combine(Directory, XmlIcon);

                        using (var fileStream = new FileStream(iconPath, FileMode.Open, FileAccess.Read))
                        {
                            var bitmapImage = new BitmapImage();

                            bitmapImage.BeginInit();
                            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                            bitmapImage.StreamSource = fileStream;
                            bitmapImage.EndInit();

                            icon = bitmapImage;
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error("Icon of Extension \"{0}\" not loaded: {1}", Name, ex.ToString());

                        // Load default icon
                        icon = new BitmapImage(new Uri(@"pack://application:,,,/Resources/DefaultExtensionIcon.png"));
                    }
                }

                return icon;
            }
        }


        #region Addon specific properties

        public string AddonPluginDependency { get; set; }
        public string AddonType { get; set; }


        #endregion


        /// <summary>
        /// Gets the localized text of Name, Description and Changelog, if available
        /// </summary>
        /// <param name="localizedText">List of localized text</param>
        /// <returns>Localized text</returns>
        private string getLocalizedText(List<LocalizedString> localizedStrings)
        {
            var currentLanguage = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
            var defaultText = localizedStrings.Where(t => string.IsNullOrEmpty(t.Language)).FirstOrDefault();
            var localizedText = localizedStrings.Where(t => t.Language == currentLanguage).FirstOrDefault();

            if (localizedText != null)
                return localizedText.Value;
            else if (defaultText != null)
                return defaultText.Value;
            else
            {
                Log.Error("Name, Description or Changelog of Extension \"{0}\" not found!", Id);
                return string.Empty;
            }
        }
    }

    public enum ExtensionType
    {
        Plugin, BackgroundPlugin, SidePlugin, Addon
    }

    public class LocalizedString
    {
        [XmlAttribute("lang")]
        public string Language { get; set; }
        [XmlText]
        public string Value { get; set; }
    }
}
